package com.mysterymall.Service.Impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.db.sql.Order;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mysterymall.Common.Comp.HttpStatus;
import com.mysterymall.Common.Utils.BaseEnum;
import com.mysterymall.Common.Utils.Result;
import com.mysterymall.Common.Utils.StringUtils;
import com.mysterymall.Mapper.*;
import com.mysterymall.Model.Dto.OrderDto;
import com.mysterymall.Model.Dto.UpdateOrderDto;
import com.mysterymall.Model.Dto.WithdrawDto;
import com.mysterymall.Model.Entity.*;
import com.mysterymall.Service.OrderInfoService;
import com.mysterymall.Service.PaymentService;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @ClassName com.mysterymall.Service.Impl
 * @Description
 * @Author HuangWX
 * @Time 2023/12/02  17:41
 */
@Service
public class OrderInfoServiceImpl implements OrderInfoService {


    private final OrderInfoMapper orderInfoMapper;

    private final MoneyTypeMapper moneyTypeMapper;

    private final BlindBoxGroupMapper blindBoxGroupMapper;

    private final UserBlindBoxGroupMapper userBlindBoxGroupMapper;

    private final BoxGroupGoodsMapper boxGroupGoodsMapper;

    private final GoodsAttributeMapper goodsAttributeMapper;

    private final GoodsMapper goodsMapper;

    private final UserGoodsMapper userGoodsMapper;

    private final GameCurrencyMapper gameCurrencyMapper;

    private final PaymentClassMapper paymentClassMapper;

    private final UserMapper userMapper;

    private final PaymentDetailMapper paymentDetailMapper;

    private final AddressMapper addressMapper;

    private final WithdrawDepositMapper withdrawDepositMapper;

    private final BankCardMapper bankCardMapper;


    /**
     * 构造器注入
     *
     * @param moneyTypeMapper         币种 mapper
     * @param blindBoxGroupMapper     盲盒 mapper
     * @param userBlindBoxGroupMapper 用户盲盒 mapper
     * @param boxGroupGoodsMapper     盲盒明细 mapper
     * @param orderInfoMapper         订单 mapper
     * @param goodsAttributeMapper    商品属性 mapper
     * @param goodsMapper             商品 mapper
     * @param userGoodsMapper         用户商品 mapper
     * @param gameCurrencyMapper      游戏币 mapper
     * @param paymentClassMapper      支付方式 mapper
     * @param userMapper              用户 mapper
     * @param paymentDetailMapper     支付明细 mapper
     * @param withdrawDepositMapper   提现 mapper
     */
    public OrderInfoServiceImpl(OrderInfoMapper orderInfoMapper, MoneyTypeMapper moneyTypeMapper, BlindBoxGroupMapper blindBoxGroupMapper,
                                UserBlindBoxGroupMapper userBlindBoxGroupMapper, BoxGroupGoodsMapper boxGroupGoodsMapper,
                                GoodsAttributeMapper goodsAttributeMapper, GoodsMapper goodsMapper, UserGoodsMapper userGoodsMapper,
                                GameCurrencyMapper gameCurrencyMapper, PaymentClassMapper paymentClassMapper, UserMapper userMapper,
                                PaymentDetailMapper paymentDetailMapper, AddressMapper addressMapper, WithdrawDepositMapper withdrawDepositMapper,
                                BankCardMapper bankCardMapper) {
        this.orderInfoMapper = orderInfoMapper;
        this.moneyTypeMapper = moneyTypeMapper;
        this.blindBoxGroupMapper = blindBoxGroupMapper;
        this.userBlindBoxGroupMapper = userBlindBoxGroupMapper;
        this.boxGroupGoodsMapper = boxGroupGoodsMapper;
        this.goodsAttributeMapper = goodsAttributeMapper;
        this.goodsMapper = goodsMapper;
        this.userGoodsMapper = userGoodsMapper;
        this.gameCurrencyMapper = gameCurrencyMapper;
        this.paymentClassMapper = paymentClassMapper;
        this.userMapper = userMapper;
        this.paymentDetailMapper = paymentDetailMapper;
        this.addressMapper = addressMapper;
        this.withdrawDepositMapper = withdrawDepositMapper;
        this.bankCardMapper = bankCardMapper;
    }


    @Override
    @Transactional
    public Map<String, Object> insertOrder(OrderDto orderDto) {

        OrderInfo orderInfo = new OrderInfo();


        Map<String, Object> map = new HashMap<>();

        // 币种
        orderInfo.setPaymentMoneyCode(moneyTypeMapper.queryByCode("MYR").getId());

        // 订单状态
        orderInfo.setOrderStatus(BaseEnum.Pending_Payment.getCode());

        // 创建人
        orderInfo.setCreateUser(StpUtil.getLoginIdAsString());

        // 修改人
        orderInfo.setUpdateUser(StpUtil.getLoginIdAsString());

        // 订单金额
        orderInfo.setGoodsOriginalPrice(new BigDecimal(0));

        // 减免金额
        orderInfo.setDiscountsAmount(new BigDecimal(0));

        // 实付金额
        orderInfo.setGoodsAmount(new BigDecimal(0));

        String id = UUID.randomUUID().toString().replaceAll("-", "");

        // 订单ID
        orderInfo.setId(id);

        // 盲盒类
        if (BaseEnum.Goods_Type_Blind_Box_Group.getCode().equals(orderDto.getGoodsType())) {

            // 订单流水
            orderInfo.setOrderCode("MH" + StringUtils.getTime("YYMMDD") + StringUtils.getRandom(6));


            // 盲盒商品数量
            orderInfo.setGoodsQuantity(orderDto.getNum());

            // 查询盲盒
            BlindBoxGroup blindBoxGroup = blindBoxGroupMapper.selectById(orderDto.getGoodsId().get(0));

            // 校验
            if (blindBoxGroup == null) {
                map.put("Result", new Result(HttpStatus.BAD_NOT_PASS, "message.ParameterError"));
                return map;
            }

            BigDecimal goodsAmount = new BigDecimal(0);

            // 计算订单金额
            switch (orderDto.getNum()) {
                case 1: {
                    goodsAmount = blindBoxGroup.getGroupAmount();
                    break;
                }
                case 3: {
                    goodsAmount = new BigDecimal(blindBoxGroup.getGroupContinuousAmount().split("_")[0]);
                    break;
                }
                case 5: {
                    goodsAmount = new BigDecimal(blindBoxGroup.getGroupContinuousAmount().split("_")[1]);
                    break;
                }

                case 10: {
                    goodsAmount = new BigDecimal(blindBoxGroup.getGroupContinuousAmount().split("_")[2]);
                    break;
                }
                default: {
                    for (int i = 0; i < orderDto.getNum(); i++) {
                        goodsAmount = goodsAmount.add(blindBoxGroup.getGroupAmount());
                    }
                }
            }

            // 归属到用户
            for (int i = 0; i < orderDto.getNum(); i++) {
                this.userGoodsControls(blindBoxGroup, orderInfo);
            }

            // 盲盒商品
            orderInfo.setLogisticsCode(blindBoxGroup.getGroupName());

            // 订单金额
            orderInfo.setGoodsAmount(goodsAmount);

            orderInfo.setGoodsOriginalPrice(goodsAmount);

            // 商品类
        } else if (BaseEnum.Goods_Type_Goods_Attribute.getCode().equals(orderDto.getGoodsType())) {

            // 订单流水
            orderInfo.setOrderCode("SP" + StringUtils.getTime("YYMMDD") + StringUtils.getRandom(6));

            // 下单商品属性
            orderInfo.setGoodsType(BaseEnum.Goods_Type_Goods_Attribute.getCode());

            // 商品数量
            orderInfo.setGoodsQuantity(orderDto.getNum());

            // 金额
            BigDecimal amount = new BigDecimal(0);

            // 保存订单地址
            Address address = addressMapper.selectOne(new LambdaQueryWrapper<Address>().eq(Address::getUserId, StpUtil.getLoginIdAsString()));

            address.setId(null);

            address.setUserId(orderInfo.getId());

            addressMapper.insert(address);

            for (int i = 0; i < orderDto.getNum(); i++) {

                // 查询商品属性
                GoodsAttribute goodsAttribute = goodsAttributeMapper.selectById(orderDto.getAttributeId().get(0));

                // 校验
                if (goodsAttribute == null) {
                    throw new RuntimeException("message.ParameterError");
                }

                orderInfo.setLogisticsCode(goodsMapper.selectById(goodsAttribute.getGoodsId()).getGoodsName());

                UserGoods userGoods = new UserGoods();

                // 商品归属到用户
                userGoods.setIsUserGoods(BaseEnum.Goods_Affiliation_User.getCode());

                // 用户ID
                userGoods.setUserId(StpUtil.getLoginIdAsString());

                // 订单ID
                userGoods.setOrderInfoId(id);

                // 商品
                Goods goods = goodsMapper.selectById(goodsAttribute.getGoodsId());

                // 商品金额
                userGoods.setGoodsAmount(goodsAttribute.getGoodsAmount());

                // 订单金额
                amount = amount.add(goodsAttribute.getGoodsAmount());

                // 实付金额
                userGoods.setGoodsAmount(goodsAttribute.getGoodsAmount());

                // 未支付成功 (暂时不显示)
                userGoods.setDeleteIsStatus(BaseEnum.Yes_Delete.getCode());

                // 商品属性名
                userGoods.setAttributeName(goodsAttribute.getAttributeName());

                // 商品属性值
                userGoods.setAttributeValue(goodsAttribute.getAttributeValue());

                // 商品图片
                userGoods.setGoodsImages(goods.getGoodsImages());

                // 商品描述图片
                userGoods.setGoodsImageDescriptZh(goods.getGoodsImageZh());

                // 商品描述图片
                userGoods.setGoodsImageDescriptMs(goods.getGoodsImageMs());

                // 商品描述图片
                userGoods.setGoodsImageDescriptEn(goods.getGoodsImageEn());

                // 商品名称
                userGoods.setGoodsName(goods.getGoodsName());

                // 商品是否兑换
                userGoods.setIsExchange(BaseEnum.Goods_Not_Exchange.getCode());

                userGoodsMapper.insert(userGoods);
            }

            // 订单实付金额
            orderInfo.setGoodsAmount(amount);


            orderInfo.setGoodsOriginalPrice(amount);

            // 游戏币类
        } else if (BaseEnum.Goods_Type_Game_Currency.getCode().equals(orderDto.getGoodsType())) {

            // 订单流水
            orderInfo.setOrderCode("YX" + StringUtils.getTime("YYMMDD") + StringUtils.getRandom(6));

            // 商品类别
            orderInfo.setGoodsType(BaseEnum.Goods_Type_Game_Currency.getCode());

            // 商品数量
            orderInfo.setGoodsQuantity(1);

            PaymentClass paymentClass = new PaymentClass();

            if (orderDto.getPaymentClassId() == null || orderDto.getPaymentClassId().isEmpty()) {
                // 支付选项
                paymentClass = paymentClassMapper.selectById("947926e8-62d2-0f0f-6527-e2d0c5414043");
                // 订单金额
                orderInfo.setGoodsOriginalPrice(orderDto.getAmount());
                //  实际付款金额
                orderInfo.setGoodsAmount(orderDto.getAmount());

                paymentClass.setAmount(orderDto.getAmount());
            } else {
                // 支付选项
                paymentClass = paymentClassMapper.selectById(orderDto.getPaymentClassId());
                // 订单金额
                orderInfo.setGoodsOriginalPrice(paymentClass.getAmount());
                //  实际付款金额
                orderInfo.setGoodsAmount(paymentClass.getAmount());
            }


            PaymentDetail paymentDetail = new PaymentDetail();

            // 支付人
            paymentDetail.setPaymentUserId(StpUtil.getLoginIdAsString());

            // 支付金额
            paymentDetail.setAmount(paymentClass.getAmount());

            // 币种
            paymentDetail.setMoneyCode(moneyTypeMapper.queryByCode("MYR").getId());

            // 订单号
            paymentDetail.setOrderId(orderInfo.getId());

            // 删除状态(不展示)
            paymentDetail.setPaymentStatus(BaseEnum.Yes_Delete.getCode());

            paymentDetailMapper.insert(paymentDetail);

        }

        // 币种
        orderInfo.setPaymentMoneyCode(moneyTypeMapper.queryByCode("MYR").getId());

        // 订单数据
        orderInfoMapper.insert(orderInfo);

        map.put("orderInfo", orderInfo);
        return map;
    }

    private static UserBlindBoxGroup getUserBlindBoxGroup(String id, BlindBoxGroup blindBoxGroup) {

        UserBlindBoxGroup userBlindBoxGroup = new UserBlindBoxGroup();

        // 用户id
        userBlindBoxGroup.setUserId(StpUtil.getLoginIdAsString());

        // 订单id
        userBlindBoxGroup.setOrderInfoId(id);

        // 盲盒名称
        userBlindBoxGroup.setGroupName(blindBoxGroup.getGroupName());

        // 盲盒图片
        userBlindBoxGroup.setGroupImages(blindBoxGroup.getGroupImages());

        // 盲盒商品概率
        userBlindBoxGroup.setGoodsQualityChance(blindBoxGroup.getGoodsQualityChance());

        // 是否逻辑删除 (未支付暂不显示)
        userBlindBoxGroup.setIsDelete(BaseEnum.Yes_Delete.getCode());

        return userBlindBoxGroup;
    }


    @Override
    public boolean cancelOrder(String orderId) {

        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);

        if (orderInfo.getOrderStatus().equals(BaseEnum.Pending_Payment.getCode())) {
            // 改为已取消
            orderInfo.setOrderStatus(BaseEnum.Cancelled.getCode());
            orderInfoMapper.updateById(orderInfo);
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public Result getAllOrder(String type, Integer currIndex, Integer pageSize, HttpServletRequest request) {

        if (!StpUtil.hasPermission("orderInfo:select:*")) {
            return new Result(HttpStatus.UNAUTHORIZED, "message.powerError");
        }

        return getOrderListControls(type, currIndex, pageSize, request, 0);
    }

    @Override
    @Transactional
    public Result getMyAllOrder(String type, Integer currIndex, Integer pageSize, HttpServletRequest request) {

        if (!StpUtil.hasPermission("orderInfo:select:my")) {
            return new Result(HttpStatus.UNAUTHORIZED, "message.powerError");
        }
        return getOrderListControls(type, currIndex, pageSize, request, 1);
    }

    @Override
    public Result getOrderInfo(String orderCode, HttpServletRequest request) {

        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderInfo::getOrderCode, orderCode);
        OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);

        if (orderInfo == null) {
            return new Result(HttpStatus.BAD_NOT_PASS, "message.orderCont.orderError");
        }
        // 判断是不是自己的订单
        if (!orderInfo.getCreateUser().equals(StpUtil.getLoginIdAsString())) {
            return new Result(HttpStatus.UNAUTHORIZED, "message.powerError");
        }

        Map<String, Object> map = new HashMap<>();

        // 订单信息
        map.put("orderInfo", this.getOrderInfoControls(orderInfo, request));

        // 收货地址
        map.put("address", addressMapper.selectOne(new LambdaQueryWrapper<Address>().eq(Address::getUserId, orderInfo.getId())));

        return new Result(HttpStatus.SUCCESS, "message.querySuccess", map);
    }

    @Override
    @Transactional
    public Result pickUpGoods(String goodsId, String addressId) {

        User user = userMapper.selectById(StpUtil.getLoginIdAsString());

        LambdaQueryWrapper<UserGoods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserGoods::getId, goodsId);
        queryWrapper.eq(UserGoods::getUserId, user.getId());
        queryWrapper.eq(UserGoods::getIsUserGoods, BaseEnum.Goods_Affiliation_User.getCode());
        UserGoods userGoods = userGoodsMapper.selectOne(queryWrapper);


        Address address = addressMapper.selectById(addressId);

        OrderInfo orderInfo = new OrderInfo();

        orderInfo.setCreateUser(user.getId());

        orderInfo.setGoodsType(BaseEnum.Goods_Type_Goods_Attribute.getCode());

        orderInfo.setGoodsQuantity(1);

        orderInfo.setGoodsOriginalPrice(userGoods.getGoodsAmount());

        orderInfo.setGoodsAmount(new BigDecimal(0));

        orderInfo.setCreateUser(user.getId());

        orderInfo.setUpdateUser(user.getId());

        orderInfo.setOrderCode("TH" + StringUtils.getTime("YYMMDD") + StringUtils.getRandom(6));

        orderInfo.setDiscountsAmount(new BigDecimal(0));

        // 待发货
        orderInfo.setOrderStatus(BaseEnum.Pending_Delivery.getCode());

        orderInfo.setPaymentMoneyCode(moneyTypeMapper.queryByCode("MYR").getId());

        orderInfoMapper.insert(orderInfo);

        userGoods.setOrderInfoId(orderInfo.getId());

        userGoods.setIsUserGoods(BaseEnum.Goods_Affiliation_Order.getCode());

        userGoodsMapper.updateById(userGoods);


        address.setId(null);
        address.setUserId(orderInfo.getId());
        addressMapper.insert(address);

        return new Result(HttpStatus.SUCCESS, "message.querySuccess");
    }

    @Override
    public Result applyForWithdrawal(BigDecimal amount) {


        // 判断金额是否大于等于20
        if (amount.compareTo(new BigDecimal(20)) < 0) {
            return new Result(HttpStatus.BAD_NOT_PASS, "message.queryError");
        }

        // 判断余额
        User user = userMapper.selectById(StpUtil.getLoginIdAsString());

        if (user.getBrokerage().compareTo(amount) < 0) {
            return new Result(HttpStatus.BAD_NOT_PASS, "message.queryError");
        }

        user.setBrokerage(user.getBrokerage().subtract(amount));

        userMapper.updateById(user);

        WithdrawDeposit withdrawDeposit = new WithdrawDeposit();

        withdrawDeposit.setWithdrawAmount(amount);

        withdrawDeposit.setUserId(StpUtil.getLoginIdAsString());

        withdrawDeposit.setWithdrawStatus(BaseEnum.Pending_Audit.getCode());


        BankCard bankCard = bankCardMapper.selectById(user.getAcquiesceBackCard());

        // 校验
        if (bankCard == null) {
            return new Result(HttpStatus.BAD_NOT_PASS, "message.queryError");
        }

        withdrawDeposit.setBankAccountNumber(bankCard.getBankAccountNumber());

        withdrawDeposit.setBankAddress(bankCard.getBankAddress());

        withdrawDeposit.setBankName(bankCard.getBankName());

        withdrawDeposit.setBeneficiaryName(bankCard.getBeneficiaryName());

        withdrawDepositMapper.insert(withdrawDeposit);

        return new Result(HttpStatus.SUCCESS, "message.querySuccess");

    }

    @Override
    public Result getWithdrawDepositList(Integer currIndex, Integer pageSize, String status) {

        Page<WithdrawDeposit> page = new Page<>();
        page.setCurrent(currIndex);
        page.setSize(pageSize);
        LambdaQueryWrapper<WithdrawDeposit> queryWrapper = new LambdaQueryWrapper<>();

        if ("all".equals(status)) {

        } else {
            queryWrapper.eq(WithdrawDeposit::getWithdrawStatus, status);
        }

        Page<WithdrawDeposit> withdrawDepositPage = withdrawDepositMapper.selectPage(page, queryWrapper);

        List<WithdrawDeposit> withdrawDepositList1 = new ArrayList<>();

        for (WithdrawDeposit withdrawDeposit : withdrawDepositPage.getRecords()) {
            withdrawDeposit.setUserId(userMapper.selectById(withdrawDeposit.getUserId()).getUserName());
            withdrawDepositList1.add(withdrawDeposit);
        }
        withdrawDepositPage.setRecords(withdrawDepositList1);

        return new Result(HttpStatus.SUCCESS, "message.querySuccess", withdrawDepositPage);
    }

    @Override
    public Map<String, Object> updateWithdrawDepositStatus(WithdrawDto withdrawDto) {

        Map<String, Object> map = new HashMap<>();
        WithdrawDeposit withdrawDeposit = withdrawDepositMapper.selectById(withdrawDto.getWithdrawId());

        if (withdrawDeposit == null) {
            map.put("Result", new Result(HttpStatus.BAD_NOT_PASS, "message.queryError"));
            return map;
        }
        if (withdrawDeposit.getWithdrawStatus().equals(BaseEnum.Pending_Audit.getCode())) {
            if (withdrawDto.getStatus().equals(BaseEnum.Audit_Not_Passed.getCode()) || withdrawDto.getStatus().equals(BaseEnum.Audit_Passed.getCode())) {
                withdrawDeposit.setWithdrawStatus(withdrawDto.getStatus());
            }
        }
        withdrawDepositMapper.updateById(withdrawDeposit);

        map.put("withdrawDeposit", withdrawDeposit);
        return map;
    }

    @Override
    public List<WithdrawDeposit> getMyWithdrawDepositList(Integer currIndex, Integer pageSize, String status) {

        Page<WithdrawDeposit> page = new Page<>();
        page.setCurrent(currIndex);
        page.setSize(pageSize);
        LambdaQueryWrapper<WithdrawDeposit> queryWrapper = new LambdaQueryWrapper<>();


        queryWrapper.eq(WithdrawDeposit::getUserId, StpUtil.getLoginIdAsString());

        if ("all".equals(status)) {

        } else {
            queryWrapper.eq(WithdrawDeposit::getWithdrawStatus, status);
        }

        List<WithdrawDeposit> withdrawDepositList = withdrawDepositMapper.selectPage(page, queryWrapper).getRecords();

        List<WithdrawDeposit> withdrawDepositList1 = new ArrayList<>();

        for (WithdrawDeposit withdrawDeposit : withdrawDepositList) {
            withdrawDeposit.setUserId(userMapper.selectById(withdrawDeposit.getUserId()).getUserName());
            withdrawDepositList1.add(withdrawDeposit);
        }

        return withdrawDepositList1;
    }

    @Override
    public void WithdrawalAndRefund(WithdrawDeposit withdrawDeposit) {

        User user = userMapper.selectById(withdrawDeposit.getUserId());

        user.setBrokerage(user.getBrokerage().add(withdrawDeposit.getWithdrawAmount()));

        userMapper.updateById(user);
    }

    @Override
    public Result queryStatus(String orderStatus, String currIndex, String pageSize) {


        return null;
    }

    @Override
    public Result updateOrderStatus(UpdateOrderDto updateOrderDto) {

        // 查询订单
        OrderInfo orderInfo = orderInfoMapper.selectById(updateOrderDto.getOrderId());

        if (orderInfo == null) {
            return new Result(HttpStatus.BAD_NOT_PASS, "message.orderCont.orderError");
        }


        if (updateOrderDto.getOrderStatus().equals(BaseEnum.Pending_Receipt.getCode())) {
            orderInfo.setOrderStatus(BaseEnum.Completed.getCode());
            orderInfoMapper.updateById(orderInfo);
            return new Result(HttpStatus.SUCCESS, "message.updateSuccess");
        } else if (updateOrderDto.getOrderStatus().equals(BaseEnum.Pending_Delivery.getCode())) {
            // 查询订单状态
            if (!orderInfo.getOrderStatus().equals(BaseEnum.Pending_Delivery.getCode())) {
                return new Result(HttpStatus.BAD_NOT_PASS, "message.orderCont.orderError");
            }

            // 修改订单状态--待收货
            orderInfo.setOrderStatus(BaseEnum.Pending_Receipt.getCode());

            orderInfo.setLogisticsCompany(updateOrderDto.getLogisticsCompany());

            orderInfo.setPatternOfPayment("");

            orderInfo.setLogisticsCode(updateOrderDto.getLogisticsCode());

            orderInfoMapper.updateById(orderInfo);

            return new Result(HttpStatus.SUCCESS, "message.updateSuccess");
        } else {
            return new Result(HttpStatus.BAD_NOT_PASS, "message.orderCont.orderError");
        }
    }

    @Override
    public void updateWithdrawDepositStatus(WithdrawDeposit withdrawDeposit) {

        String status = withdrawDeposit.getWithdrawStatus();
        // 修改提现状态
        withdrawDeposit = withdrawDepositMapper.selectById(withdrawDeposit.getId());

        withdrawDeposit.setWithdrawStatus(status);

        withdrawDepositMapper.updateById(withdrawDeposit);
    }

    @Override
    public Result getPaymentOrder(Integer currIndex, Integer pageSize, String search,HttpServletRequest request, String type,String time) {


        String[] stringList = new String[]{type,"",""};

        if(!"".equals(search)){
            stringList[1] = search;
        }

        if(!"".equals(time)){
            stringList[2] = time;
        }

        return getOrderListControls(stringList[0]+"hwx"+stringList[1]+"hwx"+stringList[2], currIndex, pageSize, request, 2);

    }

    @NotNull
    @Transactional
    public Result getOrderListControls(String type, Integer currIndex, Integer pageSize, HttpServletRequest request, Integer type1) {


        Page<OrderInfo> page = new Page<>();
        page.setCurrent(currIndex);
        page.setSize(pageSize);
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        if (type1 == 1) {
            queryWrapper.eq(OrderInfo::getCreateUser, StpUtil.getLoginIdAsString());
        }else if(type1 == 2){
            queryWrapper.eq(OrderInfo::getGoodsType, BaseEnum.Goods_Type_Game_Currency.getCode());
            String[] split = type.split("hwx");
            String search = userMapper.queryByUserName(split[1]) == null ? split[1] : userMapper.queryByUserName(split[1]).getId();
            queryWrapper.like(OrderInfo::getCreateUser, search);


            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-d HH:mm:ss");
            LocalDateTime startDate = LocalDateTime.parse(split[2].split("_")[0], formatter);
            LocalDateTime endDate = LocalDateTime.parse(split[2].split("_")[1], formatter);


            Instant startInstant = startDate.atZone(ZoneId.systemDefault()).toInstant();
            Instant endInstant = endDate.withHour(23).withMinute(59).withSecond(59)
                    .atZone(ZoneId.systemDefault()).toInstant();


            queryWrapper.between(OrderInfo::getCreateTime,startInstant, endInstant);

            type = split[0];
        }
        // 按照订单创建时间倒序
        queryWrapper.orderByDesc(OrderInfo::getCreateTime);

        Page<OrderInfo> orderInfoPage;
        if ("all".equals(type)) {
            // 查询所有订单
            orderInfoPage = orderInfoMapper.selectPage(page, queryWrapper);
        } else if ("GoodsWaitingToBeSent".equals(type)) {
            // 查询待发货订单
            queryWrapper.eq(OrderInfo::getOrderStatus, BaseEnum.Pending_Delivery.getCode());
            orderInfoPage = orderInfoMapper.selectPage(page, queryWrapper);
        } else if ("WaitToBeReceived".equals(type)) {
            // 待收货
            queryWrapper.eq(OrderInfo::getOrderStatus, BaseEnum.Pending_Receipt.getCode());
            // 且物流号不为空
            queryWrapper.isNotNull(OrderInfo::getLogisticsCompany);
            // 且物流号不为空字符串
            queryWrapper.ne(OrderInfo::getLogisticsCompany, "");
            orderInfoPage = orderInfoMapper.selectPage(page, queryWrapper);
        } else {
            // 查询指定类别的订单
            queryWrapper.eq(OrderInfo::getOrderStatus, type);
            orderInfoPage = orderInfoMapper.selectPage(page, queryWrapper);
        }

        List<OrderInfo> orderInfoList1 = new ArrayList<>();
        for (OrderInfo orderInfo : orderInfoPage.getRecords()) {

            String userId = orderInfo.getCreateUser();

            orderInfo = this.getOrderInfoControls(orderInfo, request);

            if (type1.equals(0)) {
                // 只有订单编号开头字母为TH的才有物流编码
                if (orderInfo.getOrderCode().startsWith("TH")) {
                    // 物流公司
                    orderInfo.setLogisticsCompany(orderInfo.getLogisticsCompany());
                    // 物流单号
                    orderInfo.setLogisticsCode(orderInfo.getLogisticsCode());
                } else {
                    orderInfo.setLogisticsCompany("");
                    orderInfo.setLogisticsCode("");
                }
                orderInfo.setGoodsType(userMapper.selectById(userId).getUserName());
            }else if(type1.equals(2)){
                orderInfo.setGoodsType(userMapper.selectById(userId).getUserName());
            }
            orderInfoList1.add(orderInfo);

        }
        orderInfoPage.setRecords(orderInfoList1);

        return Result.success("message.querySuccess", orderInfoPage);
    }

    public OrderInfo getOrderInfoControls(OrderInfo orderInfo, HttpServletRequest request) {

        orderInfo.setCreateUser(userMapper.selectById(orderInfo.getCreateUser()).getUserName());
        // 暂存币种
        if (orderInfo.getGoodsType().equals(BaseEnum.Goods_Type_Game_Currency.getCode())) {

            GameCurrency gameCurrency = gameCurrencyMapper.selectOne(new LambdaQueryWrapper<GameCurrency>());
            switch ((String) request.getAttribute("Lang")) {
                case "zh":
                    orderInfo.setPaymentMoneyCode(gameCurrency.getName().split("_")[0]);
                    break;
                case "ms":
                    orderInfo.setPaymentMoneyCode(gameCurrency.getName().split("_")[1]);
                    break;
                case "en":
                    orderInfo.setPaymentMoneyCode(gameCurrency.getName().split("_")[2]);
                    break;
            }

            orderInfo.setCreateUser("gameCurrency.png");
        } else if (orderInfo.getGoodsType().equals(BaseEnum.Goods_Type_Goods_Attribute.getCode())) {

            // 商品
            LambdaQueryWrapper<UserGoods> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(UserGoods::getOrderInfoId, orderInfo.getId());

            UserGoods UserGoods = userGoodsMapper.selectList(queryWrapper1).get(0);

            switch ((String) request.getAttribute("Lang")) {
                case "zh":
                    orderInfo.setPaymentMoneyCode(UserGoods.getGoodsName().split("_")[0]);
                    break;
                case "ms":
                    orderInfo.setPaymentMoneyCode(UserGoods.getGoodsName().split("_")[1]);
                    break;
                case "en":
                    orderInfo.setPaymentMoneyCode(UserGoods.getGoodsName().split("_")[2]);
                    break;
            }

            // 暂存商品图片
            orderInfo.setCreateUser(UserGoods.getGoodsImages());

        } else if (orderInfo.getGoodsType().equals(BaseEnum.Goods_Type_Blind_Box_Group.getCode())) {

            // 盲盒
            LambdaQueryWrapper<UserBlindBoxGroup> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(UserBlindBoxGroup::getOrderInfoId, orderInfo.getId());

            UserBlindBoxGroup userBlindBoxGroup = userBlindBoxGroupMapper.selectList(queryWrapper1).get(0);

            switch ((String) request.getAttribute("Lang")) {
                case "zh":
                    orderInfo.setPaymentMoneyCode(userBlindBoxGroup.getGroupName().split("_")[0]);
                    break;
                case "ms":
                    orderInfo.setPaymentMoneyCode(userBlindBoxGroup.getGroupName().split("_")[1]);
                    break;
                case "en":
                    orderInfo.setPaymentMoneyCode(userBlindBoxGroup.getGroupName().split("_")[2]);
                    break;
            }
            // 暂存商品图片--盲盒
            orderInfo.setCreateUser(userBlindBoxGroup.getGroupImages());
        }

        return orderInfo;
    }

    @Transactional
    public void userGoodsControls(BlindBoxGroup blindBoxGroup, OrderInfo orderInfo) {

        // 下单盲盒类
        orderInfo.setGoodsType(BaseEnum.Goods_Type_Blind_Box_Group.getCode());

        // 用户盲盒类
        UserBlindBoxGroup userBlindBoxGroup = getUserBlindBoxGroup(orderInfo.getId(), blindBoxGroup);

        // 未开启
        userBlindBoxGroup.setIsOpen(BaseEnum.Not_Open.getCode());

        // 盲盒金额
        userBlindBoxGroup.setGroupAmount(blindBoxGroup.getGroupAmount());

        userBlindBoxGroupMapper.insert(userBlindBoxGroup);

        // 盲盒详情
        UserGoods userGoods = new UserGoods();

        // 商品归属到盲盒
        userGoods.setIsUserGoods(BaseEnum.Goods_Affiliation_Box.getCode());

        // 盲盒id
        userGoods.setUserBlindBoxGroupId(userBlindBoxGroup.getId());

        // 查询盲盒明细
        LambdaQueryWrapper<BoxGroupGoods> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(BoxGroupGoods::getGroupId, blindBoxGroup.getId());

        // 盲盒明细
        List<BoxGroupGoods> boxGroupGoodsList = boxGroupGoodsMapper.selectList(queryWrapper);

        for (BoxGroupGoods boxGroupGoods : boxGroupGoodsList) {

            userGoods.setId(null);

            // 商品品质
            userGoods.setGoodsQuality(boxGroupGoods.getGoodsQuality());

            // 商品属性
            GoodsAttribute goodsAttribute = goodsAttributeMapper.selectById(boxGroupGoods.getGoodsAttributeId());

            // 商品金额
            userGoods.setGoodsAmount(goodsAttribute.getGoodsAmount());

            // 商品属性名
            userGoods.setAttributeName(goodsAttribute.getAttributeName());

            // 商品属性值
            userGoods.setAttributeValue(goodsAttribute.getAttributeValue());

            // 商品
            Goods goods = goodsMapper.selectById(goodsAttribute.getGoodsId());

            // 商品图片
            userGoods.setGoodsImages(goods.getGoodsImages());


            // 商品描述图
            userGoods.setGoodsImageDescriptZh(goods.getGoodsImageZh());

            // 商品描述图
            userGoods.setGoodsImageDescriptMs(goods.getGoodsImageMs());

            // 商品描述图
            userGoods.setGoodsImageDescriptEn(goods.getGoodsImageEn());

            // 商品名称
            userGoods.setGoodsName(goods.getGoodsName());

            userGoods.setDeleteIsStatus(BaseEnum.Yes_Delete.getCode());

            userGoodsMapper.insert(userGoods);
        }
    }
}
